import React, { useState } from 'react';
import { Form, Button, Card, Alert, Container } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import AuthService from '../services/AuthService';

const Register = () => {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [fullName, setFullName] = useState('');
  const [role, setRole] = useState('ROLE_USER');
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [successful, setSuccessful] = useState(false);
  const navigate = useNavigate();

  const validateForm = () => {
    if (!username || !password || !confirmPassword || !fullName) {
      setMessage('请填写所有必填字段');
      return false;
    }
    if (password !== confirmPassword) {
      setMessage('两次输入的密码不一致');
      return false;
    }
    if (password.length < 6) {
      setMessage('密码长度至少为6个字符');
      return false;
    }
    return true;
  };

  const handleRegister = (e) => {
    e.preventDefault();
    setMessage('');
    setSuccessful(false);
    setLoading(true);

    if (!validateForm()) {
      setLoading(false);
      return;
    }

    const registerMethod = role === 'ROLE_ADMIN'
        ? AuthService.registerAdmin
        : AuthService.register;

    registerMethod(username, email, password, fullName)
        .then(response => {
          if (response.data.code === 200) {
            setMessage(role === 'ROLE_ADMIN' ? '管理员注册成功！' : '用户注册成功！您现在可以登录了');
            setSuccessful(true);
            setTimeout(() => navigate('/login'), 2000);
          } else {
            setMessage(response.data.message || '注册失败，请稍后再试');
            setSuccessful(false);
            setLoading(false);
          }
        })
        .catch(error => {
          const resMessage = (error.response?.data?.message ||
              error.message ||
              error.toString());
          setMessage(resMessage);
          setSuccessful(false);
          setLoading(false);
        });
  };

  return (
      <Container className="d-flex justify-content-center align-items-center min-vh-100">
        <Card className="shadow rounded-4 p-5 w-100" style={{ maxWidth: '450px' }}>
          <Card.Body className="px-5">
            <div className="text-center mb-5">
              <h2 className="fw-bold text-gray-800">账号注册</h2>
              <p className="text-muted mt-2">请填写以下信息创建账户</p>
            </div>

            {message && (
                <Alert
                    variant={successful ? "success" : "danger"}
                    className="mb-4 rounded-3 shadow-sm"
                    style={{
                      padding: '12px',
                      backgroundColor: successful ? '#e6f5e6' : '#ffe6e6',
                      borderColor: successful ? '#ccf2cc' : '#ffcccc'
                    }}
                >
                  {successful ? <i className="fa fa-check-circle me-2"></i> : <i className="fa fa-exclamation-triangle me-2"></i>}
                  {message}
                </Alert>
            )}

            <Form onSubmit={handleRegister}>
              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">账号类型*</Form.Label>
                <Form.Select
                    value={role}
                    onChange={(e) => setRole(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                >
                  <option value="ROLE_USER">普通用户</option>
                  <option value="ROLE_ADMIN">管理员</option>
                </Form.Select>
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">用户名*</Form.Label>
                <Form.Control
                    type="text"
                    placeholder="请输入用户名（必填）"
                    value={username}
                    onChange={(e) => setUsername(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">电子邮箱</Form.Label>
                <Form.Control
                    type="email"
                    placeholder="可选（建议填写）"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                />
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">全名*</Form.Label>
                <Form.Control
                    type="text"
                    placeholder="请输入真实姓名（必填）"
                    value={fullName}
                    onChange={(e) => setFullName(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">密码*</Form.Label>
                <Form.Control
                    type="password"
                    placeholder="至少6位字符（必填）"
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Form.Group className="mb-4">
                <Form.Label className="fw-semibold text-gray-700">确认密码*</Form.Label>
                <Form.Control
                    type="password"
                    placeholder="请再次输入密码（必填）"
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    disabled={loading}
                    className="rounded-3 shadow-sm"
                    style={{ height: '50px' }}
                    required
                />
              </Form.Group>

              <Button
                  variant="success"
                  type="submit"
                  className="w-100 py-2 fs-5 rounded-3 shadow-sm"
                  disabled={loading}
              >
                {loading ? '注册中...' : role === 'ROLE_ADMIN' ? '注册管理员' : '注册用户'}
              </Button>
            </Form>

            <div className="mt-4 text-center">
              <span className="text-muted me-1">已有账号？</span>
              <Button
                  variant="link"
                  className="text-success fw-semibold p-0"
                  onClick={() => navigate('/login')}
                  disabled={loading}
              >
                点击前往登录
              </Button>
            </div>
          </Card.Body>
        </Card>
      </Container>
  );
};

export default Register;